package com.hottv.meeting.videomeeting;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.herewhite.sdk.Room;
import com.herewhite.sdk.WhiteBroadView;
import com.herewhite.sdk.domain.EventEntry;
import com.herewhite.sdk.domain.EventListener;
import com.herewhite.sdk.domain.Promise;
import com.herewhite.sdk.domain.SDKError;
import com.herewhite.sdk.domain.Scene;
import com.hottv.meeting.videomeeting.common.MeetingConfig;
import com.hottv.meeting.videomeeting.common.MeetingUtils;
import com.hottv.meeting.videomeeting.module.agora.AgoraConfig;
import com.hottv.meeting.videomeeting.module.agora.AgoraManager;
import com.hottv.meeting.videomeeting.module.agora.AgoraUtils;
import com.hottv.meeting.videomeeting.module.agora.data.MsgInfo;
import com.hottv.meeting.videomeeting.module.agora.data.MsgItem;
import com.hottv.meeting.videomeeting.module.agora.view.MemAdapter;
import com.hottv.meeting.videomeeting.module.agora.view.MsgAdapter;
import com.hottv.meeting.videomeeting.module.edp.EDPUtils;
import com.hottv.meeting.videomeeting.module.edp.data.MeetingInfo;
import com.hottv.meeting.videomeeting.module.file.activity.FolderActivity;
import com.hottv.meeting.videomeeting.module.meeting.InfoAccessImpl;
import com.hottv.meeting.videomeeting.module.meeting.MeetingAPI;
import com.hottv.meeting.videomeeting.module.meeting.MeetingManager;
import com.hottv.meeting.videomeeting.module.meeting.data.MeetInfo;
import com.hottv.meeting.videomeeting.module.meeting.data.MeetingMem;
import com.hottv.meeting.videomeeting.module.white.DoCallback;
import com.hottv.meeting.videomeeting.module.white.WhiteManager;
import com.hottv.meeting.videomeeting.module.white.WhiteUtils;
import com.hottv.meeting.videomeeting.module.white.data.ItemInfo;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import io.agora.AgoraAPI;
import io.agora.AgoraAPIOnlySignal;
import io.agora.rtc.Constants;
import io.agora.rtc.IRtcEngineEventHandler;
import io.agora.rtc.RtcEngine;
import io.agora.rtc.video.VideoCanvas;
import io.agora.rtc.video.VideoEncoderConfiguration;

import static com.hottv.meeting.videomeeting.common.MeetingConfig.EVENT_NAME;

public class MeetingActivity extends AppCompatActivity {

    private String mRoomId;
    private int mUserId;
    private Context mContext;

    private RelativeLayout mBcLayout;
    private RelativeLayout mAuLayout;
    private Button mBtnUpload;
//    private Button mBtnConnect;

    private RtcEngine mRtcEngine;

    private AgoraAPIOnlySignal mAgoraSigAPI;

    private TextView mMeetingTitle;
    private TextView mMeetingTime;
    private EditText mEditText;
    private TextView mTxtPage;


    private WhiteBroadView mWhiteView;
    private ListView mListViewMsg;
    private MemAdapter mMemAdapter;
    private ListView mListViewMem;
    private MsgAdapter mMsgAdapter;



    private IRtcEngineEventHandler mRtcEventHandler =new IRtcEngineEventHandler() {
        @Override
        public void onWarning(int warn) {
            super.onWarning(warn);
        }

        @Override
        public void onError(int err) {
            super.onError(err);
        }

        @Override
        public void onStreamMessage(int uid, int streamId, byte[] data) {
            Log.i(MeetingConfig.TAG,"onStreamMessage,uid:"+uid+",streamId:"+streamId+"");
        }

        @Override
        public void onStreamMessageError(int uid, int streamId, int error, int missed, int cached) {
            Log.e(MeetingConfig.TAG,"onStreamMessageError,uid:"+uid+",streamId:"+streamId+",error:"+error);
        }

        @Override
        public void onJoinChannelSuccess(String channel, int uid, int elapsed) {
            super.onJoinChannelSuccess(channel, uid, elapsed);
            Log.i(MeetingConfig.TAG,"onJoinChannelSuccess"+",channel:"+channel+",uid:"+uid+",elapsed"+elapsed);

        }

        @Override
        public void onRejoinChannelSuccess(String channel, int uid, int elapsed) {
            super.onRejoinChannelSuccess(channel, uid, elapsed);
            Log.i(MeetingConfig.TAG,"onJoinChannelSuccess"+",channel:"+channel+",uid:"+uid+",elapsed"+elapsed);
        }

        @Override
        public void onLeaveChannel(RtcStats stats) {
            super.onLeaveChannel(stats);
            Log.i(MeetingConfig.TAG,"onLeaveChannel"+",channel:"+stats.toString());
        }

        @Override
        public void onUserJoined(int uid, int elapsed) {
            super.onUserJoined(uid, elapsed);

            Log.i(MeetingConfig.TAG,"onUserJoined"+",uid:"+uid+",elapsed"+elapsed);

            //显示视频内容
            doRenderRemoteUi(uid);

        }

        @Override
        public void onUserOffline(int uid, int reason) {
            super.onUserOffline(uid, reason);
            Log.i(MeetingConfig.TAG,"onUserOffline"+",uid:"+uid+",reason"+String.valueOf(reason));

            doRemoveRemoteUi(uid);
        }

        @Override
        public void onFirstRemoteAudioFrame(int uid, int elapsed) {
            super.onFirstRemoteAudioFrame(uid, elapsed);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_meeting);

        initUI();

        final View layout = findViewById(Window.ID_ANDROID_CONTENT);
        ViewTreeObserver vto = layout.getViewTreeObserver();
        vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                    layout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                } else {
                    layout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                }

                new Handler().postDelayed(new Runnable(){
                    public void run(){
                        //execute the task
                        initUIandEvent();
                    }
                },500);

//                initUIandEvent();
            }
        });
    }

    @Override
    protected void onResume()
    {
        super.onResume();
        InfoAccessImpl.getInstance(mContext);
    }

    @Override
    protected void onDestroy() {
        InfoAccessImpl.getInstance(mContext).unbindAuthService();
        deInitUIandEvent();
        super.onDestroy();
    }

    private void deInitUIandEvent()
    {
        Log.i(MeetingConfig.TAG,"------deInitUIandEvent--------------------");

        //退出频道
        if (mRtcEngine != null) {
            mRtcEngine.leaveChannel();

            mRtcEngine=null;
        }
        Log.i(MeetingConfig.TAG,"------退出频道--------------------");
        AgoraManager.getInstance().destoryRTC();

        if(mAgoraSigAPI!=null)
        {
            mAgoraSigAPI.channelLeave(mRoomId);
            mAgoraSigAPI =null;
        }

        Log.i(MeetingConfig.TAG,"------退出消息--------------------");
        AgoraManager.getInstance().lougout();

        mUuid = "";

        if(mRoom!=null)
        {
            mRoom.disconnect();
            mRoom =null;
        }
        Log.i(MeetingConfig.TAG,"------退出房间--------------------");
        MeetingManager.getInstance().destroy();

    }



    private void initUIandEvent() {
        //初始化声网
        runOnUiThread(new Runnable() {
            @Override
            public void run() {

                mRtcEngine = AgoraManager.getInstance().initEngine(mContext, mRtcEventHandler);
                AgoraManager.getInstance().clearUserMap();

                //初始化消息
                mAgoraSigAPI = AgoraManager.getInstance().initSigSdk(mContext);


                Intent i = getIntent();
                String data = i.getStringExtra(MeetingConfig.MeetingDATA);
                //主叫页面
                if(!TextUtils.isEmpty(data))
                {
                    Log.i(MeetingConfig.TAG,"data:"+data);

                    Gson gson =new Gson();
                    MeetInfo info = gson.fromJson(data,MeetInfo.class);
                    MeetingManager.getInstance().AddMem(info);

                    //检测one-net平台是否联通
                    if(TextUtils.isEmpty(EDPUtils.edp_devices_Id))
                    {
                        Toast.makeText(mContext,"one-net平台尚未连接，请重试",Toast.LENGTH_LONG).show();
                        return;
                    }

                    //请求数据
                    MeetingUtils.getMeetingInfo(mContext, new DoCallback() {
                        @Override
                        public void onSuccess(String info) {
                            // 推送发送数据
                            Log.i(MeetingConfig.TAG,"pushMsgMeetingMem onSuccess meetingId:"+info);
//                            MeetingUtils.pushMsgMeetingMem(mContext,info);

                            // 初始化页面
                            initCallView(info);
                        }

                        @Override
                        public void onFailor(String info) {

                            Toast.makeText(mContext,"创建会议失败",Toast.LENGTH_LONG).show();
                        }

                        @Override
                        public void onProcess(String info) {

                        }
                    });
                }
                else   //被叫页面
                {
                    String incallData = i.getStringExtra(MeetingConfig.MeetingDATA_Incall);
                    Log.i(MeetingConfig.TAG,"incall data:"+incallData);

                    Gson gson =new Gson();
                    MeetingInfo info = gson.fromJson(incallData,MeetingInfo.class);

                    final String meetingId = info.content.meetingId;

                    MeetingUtils.joinMeeting(mContext, meetingId, new DoCallback() {
                        @Override
                        public void onSuccess(String info) {
                            //开启被叫页面
                            initInCallView(meetingId);
                        }

                        @Override
                        public void onFailor(String info) {
                            Toast.makeText(mContext,"创建会议失败",Toast.LENGTH_LONG).show();
                        }

                        @Override
                        public void onProcess(String info) {

                        }
                    });
                }
            }
        });
    }

    private void initCallView(final  String meetingId)
    {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mRoomId = meetingId;
                mUserId = Integer.parseInt(EDPUtils.edp_devices_Id) ;

                //处理声网消息
                handleMsg();

                //设置声网配置文件
                doConfigEngine(MeetingConfig.BROADCASTER_TYPE);


                handleBroadcasterUI();
                handleBroadcaster();

//                handleWhite(MeetingUtils.white_minitoken,MeetingUtils.white_uuid,true);
                joinRoom(MeetingUtils.white_uuid,MeetingUtils.white_roomtoken,true);
            }
        });

    }

    private void initInCallView(final String meetingId)
    {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mRoomId = meetingId;
                mUserId = Integer.parseInt(EDPUtils.edp_devices_Id) ;

                //处理声网消息
                handleMsg();

                //设置声网配置文件
                doConfigEngine(MeetingConfig.BROADCASTER_TYPE);

                handleAudienceUI();
                handleBroadcaster();
//                handleWhite(MeetingUtils.white_minitoken,MeetingUtils.white_uuid,false);
                joinRoom(MeetingUtils.white_uuid,MeetingUtils.white_roomtoken,false);
            }
        });
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        if(isFinishing())
            return;
        checkSelfPermissions();
    }

    private boolean checkSelfPermissions() {
        return MeetingUtils.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO, MeetingConfig.PERMISSION_REQ_ID_RECORD_AUDIO) &&
                MeetingUtils.checkSelfPermission(this,Manifest.permission.CAMERA, MeetingConfig.PERMISSION_REQ_ID_CAMERA) &&
                MeetingUtils.checkSelfPermission(this,Manifest.permission.WRITE_EXTERNAL_STORAGE, MeetingConfig.PERMISSION_REQ_ID_WRITE_EXTERNAL_STORAGE);
    }

    @Override
    public boolean onKeyDown (int keyCode, KeyEvent event)
    {
        Log.i(MeetingConfig.TAG,"dispatchKeyEvent key:"+keyCode);
        if(keyCode == MeetingConfig.key_down_action){
            boolean stillProcess = WhiteManager.getInstance().checkProcess();
            if(stillProcess)
            {
                Toast.makeText(mContext,"剩下的还在处理中",Toast.LENGTH_LONG).show();
            }
            else
            {
              int nextCur = WhiteManager.getInstance().getNextPageCur();
              if(nextCur!=-1)
              {
                  if(mRoom!=null) {
                      mRoom.setScenePath(MeetingConfig.SCENE_DIR + "/" + String.valueOf(nextCur));
                      mTxtPage.setText("当前页："+(WhiteManager.getInstance().getCurrentPage()+1)+"/"+WhiteManager.getInstance().getTotalPage());

                  }
              }else
              {
                  Toast.makeText(mContext,"已经是最后一页了",Toast.LENGTH_LONG).show();
              }
            }


            /*隐藏软键盘*/
            return true;
        }
        else if(keyCode== MeetingConfig.key_up_action)
        {
            int nextCur = WhiteManager.getInstance().getBeforePageCur();
            if(nextCur!=-1)
            {
                if(mRoom!=null) {
                    mTxtPage.setText("当前页："+(WhiteManager.getInstance().getCurrentPage()+1)+"/"+WhiteManager.getInstance().getTotalPage());
                    mRoom.setScenePath(MeetingConfig.SCENE_DIR + "/" + String.valueOf(nextCur));
                }
            }else
            {
               Toast.makeText(mContext,"已经是第一页了",Toast.LENGTH_LONG).show();
            }

            return true;
        }
        return super.onKeyDown(keyCode,event);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String permissions[], @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        Log.d(MeetingConfig.TAG,"" + requestCode + " " + Arrays.toString(permissions) + " " + Arrays.toString(grantResults));
        switch (requestCode) {
            case MeetingConfig.PERMISSION_REQ_ID_RECORD_AUDIO: {
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    MeetingUtils.checkSelfPermission(this,Manifest.permission.CAMERA, MeetingConfig.PERMISSION_REQ_ID_CAMERA);
                } else {
                    finish();
                }
                break;
            }
            case MeetingConfig.PERMISSION_REQ_ID_CAMERA: {
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    MeetingUtils.checkSelfPermission(this,Manifest.permission.WRITE_EXTERNAL_STORAGE, MeetingConfig.PERMISSION_REQ_ID_WRITE_EXTERNAL_STORAGE);

                } else {
                    finish();
                }
                break;
            }
            case MeetingConfig.PERMISSION_REQ_ID_WRITE_EXTERNAL_STORAGE: {
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                } else {
                    finish();
                }
                break;
            }
        }
    }


    private void initUI()
    {
        mContext = this;

        mWhiteView = (WhiteBroadView) findViewById(R.id.white_content);

        mBtnUpload = (Button) findViewById(R.id.btn_upload);

//        mBtnConnect = (Button) findViewById(R.id.btn_connect);

        mBcLayout = (RelativeLayout) findViewById(R.id.video_broadcaster);

        mAuLayout = (RelativeLayout) findViewById(R.id.video_audi);

        mMeetingTitle = (TextView) findViewById(R.id.txt_meeting_title);

        mMeetingTime = (TextView) findViewById(R.id.txt_time_cost);

        mEditText = (EditText) findViewById(R.id.edit_msg);

        mTxtPage = (TextView) findViewById(R.id.txt_page);
        mTxtPage.setText("当前页：0/0");

        mListViewMem = (ListView) findViewById(R.id.list_view_members);
        mListViewMsg = (ListView) findViewById(R.id.list_view_msg);

        mListViewMsg.setVisibility(View.VISIBLE);
        mListViewMem.setVisibility(View.INVISIBLE);

        TextView txtMsg = (TextView) findViewById(R.id.txt_msg);
        txtMsg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mListViewMsg.setVisibility(View.VISIBLE);
                mListViewMem.setVisibility(View.INVISIBLE);
            }
        });

        TextView txtMem = (TextView) findViewById(R.id.txt_mem);
        txtMem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mListViewMsg.setVisibility(View.INVISIBLE);
                mListViewMem.setVisibility(View.VISIBLE);
            }
        });

        List<MsgItem> msgList = new ArrayList<>();
        mMsgAdapter = new MsgAdapter(mContext,msgList);
        mListViewMsg.setAdapter(mMsgAdapter);
        mListViewMsg.setSelection(ListView.FOCUS_DOWN);

        List<String> memList = new ArrayList<>();
        mMemAdapter = new MemAdapter(mContext,memList);
        mListViewMem.setAdapter(mMemAdapter);

        mListViewMem.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

               String deviceId = MeetingManager.getInstance().getDeviceIdFromPostion(position);

               Log.i(MeetingConfig.TAG,"setOnItemClickListener,tag:"+position+",deviceId:"+deviceId);
               if(TextUtils.isEmpty(deviceId))
               {
                   Log.i(MeetingConfig.TAG,"-------deviceId is null-----------");
                   return;
               }


               int uid = 0;
               try{
                   uid = Integer.parseInt(deviceId);
               }catch (Exception e)
               {
                   e.printStackTrace();
               }

               changeSurface(uid);
            }
        });

    }

    //处理声网音视频本地
    private void handleBroadcaster()
    {
        SurfaceView surfaceView = MeetingManager.getInstance().getSurfaceViewById(mUserId);
        if(surfaceView==null) {
            surfaceView = RtcEngine.CreateRendererView(getApplicationContext());
            mAuLayout.addView(surfaceView,new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            MeetingManager.getInstance().insertSurfaceView(mUserId,surfaceView);
        }


        mRtcEngine.setupLocalVideo(new VideoCanvas(surfaceView, VideoCanvas.RENDER_MODE_HIDDEN, mUserId));
        mRtcEngine.startPreview();

        mRtcEngine.joinChannel(null,mRoomId,"OpenLive",mUserId);
    }

    private void handleBroadcasterUI()
    {
        mBtnUpload.setVisibility(View.VISIBLE);

        mBtnUpload.setFocusable(true);
        mBtnUpload.setFocusableInTouchMode(true);
        mBtnUpload.requestFocus();

        mBtnUpload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MeetingActivity.this,FolderActivity.class);
                startActivityForResult(intent,1);
//                upLoadWhite(MeetingUtils.storage_url,"/sdcard/download/08宋超.ppt");
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent bundle) {
        super.onActivityResult(requestCode, resultCode, bundle);
        Log.i(MeetingConfig.TAG, "requestCode: " + requestCode + "; resultCode: " + resultCode);
        if (resultCode == RESULT_OK) {
            String filePath  = bundle.getStringExtra("file");
            Log.i(MeetingConfig.TAG, "upLoad White filePath: " + filePath);
            upLoadWhite(MeetingUtils.storage_url,"/sdcard/download/08宋超.ppt");
        }
    }

    private void upLoadWhite(String url,String filePath)
    {
        if(mRoom!=null)
        {
            WhiteUtils.getPNG(url,filePath, new DoCallback() {

                @Override
                public void onSuccess(String info) {

                    Log.i(MeetingConfig.TAG,"onSuccess!!!!!!!!!!");
                    Scene[] scenes = WhiteManager.getInstance().getLeftScene();
                    if(scenes!=null)
                    {
                        mRoom.putScenes(MeetingConfig.SCENE_DIR,scenes,Integer.MAX_VALUE);
                    }
                }

                @Override
                public void onFailor(String info) {

                }

                @Override
                public void onProcess(String info) {

                    Log.i(MeetingConfig.TAG,"process!!!!!!!!!!");
                    Scene[] scenes = WhiteManager.getInstance().getInitScene();
                            if(scenes!=null)
                            {
                                Log.i(MeetingConfig.TAG,"num:"+scenes.length);
                                mRoom.putScenes(MeetingConfig.SCENE_DIR,scenes,0);
                                mRoom.setScenePath(MeetingConfig.SCENE_DIR+"/"+String.valueOf(0));

                                ItemInfo pptInfo =  WhiteManager.getInstance().getCurrentPageInfo();

                                double scale = 1.0d;
                                if(pptInfo!=null&&pptInfo.height>0&&pptInfo.width>0)
                                {
                                    if((pptInfo.height/pptInfo.width) >(MeetingConfig.ppt_heigh/MeetingConfig.ppt_width))
                                    {
                                        scale = (double) (MeetingConfig.ppt_heigh-50) /pptInfo.height;
                                    }
                                    else
                                    {
                                        scale = (double) (MeetingConfig.ppt_width-50)/pptInfo.width;
                                    }
                                    Log.i(MeetingConfig.TAG,"scale :"+scale);
                                    mRoom.zoomChange(scale);

                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            int current = WhiteManager.getInstance().getCurrentPage()+1;
                                            int totoal = WhiteManager.getInstance().getTotalPage();
                                            mTxtPage.setText("当前页："+current+"/"+totoal);
                                        }
                                    });
                                }
                            }
                        }
            });
        }else
        {
            Toast.makeText(mContext,"白板未初始化，请稍等",Toast.LENGTH_LONG).show();
        }
    }

    private void handleMsg()
    {
        Log.i(MeetingConfig.TAG,"handleMsg login:mRoomId"+mRoomId+",mUserId:"+mUserId);
        String appId = mContext.getString(R.string.agora_app_id);
        String account = EDPUtils.edp_devices_Id;
        mAgoraSigAPI.login2(appId,account,"_no_need_token",0,"",2,1);

        mAgoraSigAPI.callbackSet(new AgoraAPI.CallBack() {

            @Override
            public void onLoginSuccess(int var1, int var2){
                Log.i(MeetingConfig.TAG,"onLoginSuccess:"+var1);
                Log.i(MeetingConfig.TAG,"channelJoin meetingId:"+mRoomId);
                mAgoraSigAPI.channelJoin(mRoomId);
           }

            @Override
            public void onLoginFailed(int var1){
                Log.i(MeetingConfig.TAG,"onLoginFailed:"+var1);
            }

            @Override
            public void onChannelUserJoined(String account, int uid) {
                super.onChannelUserJoined(account, uid);
                Log.i(MeetingConfig.TAG,"onChannelUserJoined:"+account+",uid:"+uid);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                    }
                });
            }

            @Override
            public void onChannelUserLeaved(String account, int uid) {
                super.onChannelUserLeaved(account, uid);
                Log.i(MeetingConfig.TAG,"onChannelUserLeaved:"+account+",uid:"+uid);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                    }
                });
            }

            @Override
            public void onLogout(final int i) {
                Log.i(MeetingConfig.TAG,"onLogout:,i:"+i);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                    }
                });

            }


            @Override
            public void onQueryUserStatusResult(final String name, final String status) {
                Log.i(MeetingConfig.TAG, "onQueryUserStatusResult  name = " + name + "  status = " + status);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                    }
                });
            }

            @Override
            public void onMessageInstantReceive(final String account, int uid, final String msg) {
                Log.i(MeetingConfig.TAG, "onMessageInstantReceive  account = " + account + " uid = " + uid + " msg = " + msg);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        AgoraManager.getInstance().addMsgItem(String.valueOf(account),msg);
                        mMsgAdapter.setList(AgoraManager.getInstance().getMsgList());
                    }
                });
            }

            @Override
            public void onMessageChannelReceive(String channelID, final String account, int uid, final String msg) {
                Log.i(MeetingConfig.TAG, "onMessageChannelReceive  account = " + account + " uid = " + uid + " msg = " + msg);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        AgoraManager.getInstance().addMsgItem(String.valueOf(account),msg);
                        mMsgAdapter.setList(AgoraManager.getInstance().getMsgList());
                    }
                });
            }

            @Override
            public void onMessageSendSuccess(String messageID) {
                Log.i(MeetingConfig.TAG,"onMessageSendSuccess："+messageID);
            }

            @Override
            public void onMessageSendError(String messageID, int ecode) {
                Log.i(MeetingConfig.TAG,"onMessageSendError:"+messageID);
            }

            @Override
            public void onError(String name, int ecode, String desc) {
                Log.i(MeetingConfig.TAG, "onError  name = " + name + " ecode = " + ecode + " desc = " + desc);
            }

            @Override
            public void onLog(String txt) {
                super.onLog(txt);
            }
        });
    }

//    //处理白板
//    private void handleWhiteBroastcaster()
//    {
//        WhiteUtils.createRoom("test white", new DoCallback() {
//            @Override
//            public void onSuccess(String info) {
//                JsonObject room = new Gson().fromJson(info, JsonObject.class);
//                final String uuid = room.getAsJsonObject("msg").getAsJsonObject("room").get("uuid").getAsString();
//                final String roomToken = room.getAsJsonObject("msg").get("roomToken").getAsString();
//                mUuid = uuid;
//                Log.i(MeetingConfig.TAG,"create room,uuid:"+uuid+",roomToken:"+roomToken);
//                WhiteUtils.joinRoom(mContext, uuid, roomToken, mWhiteView, new Promise<Room>() {
//                    @Override
//                    public void then(Room room) {
//                        Log.i(MeetingConfig.TAG,"broastcaseter join in room success");
//                        mRoom = room;
//
//                        mRoom.addMagixEventListener(EVENT_NAME, new EventListener() {
//                            @Override
//                            public void onEvent(EventEntry eventEntry) {
//                                Log.i(MeetingConfig.TAG,"customEvent payload: " + eventEntry.getPayload().toString());
//
//                            }
//                        });
//
//
//
//                        MsgInfo info =new MsgInfo(AgoraConfig.MSG_NO_WHITE_URL,String.valueOf(mUserId),uuid);
//                        Log.i(MeetingConfig.TAG,"sendChannelMessage"+info.toStr());
//                        mAgoraSigSdk.sendChannelMessage(System.currentTimeMillis(),info.toStr());
//                    }
//
//                    @Override
//                    public void catchEx(SDKError sdkError) {
//                        Log.e(MeetingConfig.TAG,sdkError.getJsStack());
//                    }
//                });
//            }
//
//            @Override
//            public void onFailor(String info) {
//
//            }
//
//            @Override
//            public void onProcess(String info) {
//
//            }
//        });
//    }
//
//    private void handleWhite(String uuid,final boolean isWrite)
//    {
//        if(uuid.equals(mUuid))
//        {
//            Log.i(MeetingConfig.TAG,"uuid is exist!!!");
//            return;
//        }
//
//        mUuid = uuid;
//
//        WhiteUtils.getRoomToken(mUuid, new DoCallback() {
//            @Override
//            public void onSuccess(String info) {
//
//                Log.i(MeetingConfig.TAG,"create room,uuid:"+mUuid+",roomToken:"+info);
//                WhiteUtils.joinRoom(mContext, mUuid, info, mWhiteView, new Promise<Room>() {
//                    @Override
//                    public void then(Room room) {
//                        Log.i(MeetingConfig.TAG,"broastcaseter join in room success");
//                        mRoom = room;
//
//                        mRoom.addMagixEventListener(EVENT_NAME, new EventListener() {
//                            @Override
//                            public void onEvent(EventEntry eventEntry) {
//                                Log.i(MeetingConfig.TAG,"customEvent payload: " + eventEntry.getPayload().toString());
//                            }
//                        });
//
//                        if(isWrite)
//                        {
//                            WhiteUtils.broadcast(mRoom);
//                        }
//                        else
//                        {
//                            WhiteUtils.readonly(mRoom);
//                        }
//
//                    }
//
//                    @Override
//                    public void catchEx(SDKError sdkError) {
//                        Log.e(MeetingConfig.TAG,sdkError.getJsStack());
//                    }
//                });
//            }
//
//            @Override
//            public void onFailor(String info) {
//
//            }
//
//            @Override
//            public void onProcess(String info) {
//
//            }
//        });
//    }

    private String mUuid="";
    private Room mRoom;
    private void joinRoom(String uuid,String rooomToken,final boolean isWrite)
    {
        if(uuid.equals(mUuid))
        {
            Log.i(MeetingConfig.TAG,"uuid is exist!!!");
            return;
        }

        mUuid = uuid;

        Log.i(MeetingConfig.TAG,"join room,uuid:"+mUuid+",roomToken:"+rooomToken);
        WhiteUtils.joinRoom(mContext, mUuid, rooomToken, mWhiteView, new Promise<Room>() {
            @Override
            public void then(Room room) {
                Log.i(MeetingConfig.TAG,"broastcaseter join in room success");
                mRoom = room;

                mRoom.addMagixEventListener(EVENT_NAME, new EventListener() {
                    @Override
                    public void onEvent(EventEntry eventEntry) {
                        Log.i(MeetingConfig.TAG,"customEvent payload: " + eventEntry.getPayload().toString());
                    }
                });

                if(isWrite)
                {
                    WhiteUtils.broadcast(mRoom);
                }
                else
                {
                    WhiteUtils.readonly(mRoom);
                }

            }

            @Override
            public void catchEx(SDKError sdkError) {
                Log.e(MeetingConfig.TAG,sdkError.getJsStack());
            }
        });

    }

    private void handleAudience()
    {
        Log.i(MeetingConfig.TAG,"handleAudience start join live room");
        mRtcEngine.joinChannel(null,mRoomId,"OpenLive",mUserId);
    }

    private void doConfigEngine(int cRole) {
        int prefIndex =  MeetingConfig.DEFAULT_PROFILE_IDX;
        VideoEncoderConfiguration.VideoDimensions dimension = MeetingConfig.VIDEO_DIMENSIONS[prefIndex];

        mRtcEngine.setVideoEncoderConfiguration(new VideoEncoderConfiguration(dimension,
                VideoEncoderConfiguration.FRAME_RATE.FRAME_RATE_FPS_24,
                VideoEncoderConfiguration.STANDARD_BITRATE,
                VideoEncoderConfiguration.ORIENTATION_MODE.ORIENTATION_MODE_ADAPTIVE));
        mRtcEngine.setClientRole(cRole);
    }
    private void handleAudienceUI()
    {
        mBtnUpload.setVisibility(View.INVISIBLE);
    }

    private void doRemoveRemoteUi(final  int uid)
    {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {

                SurfaceView surfaceView = MeetingManager.getInstance().getSurfaceViewById(uid);
                if(surfaceView!=null)
                {
                    Log.i(MeetingConfig.TAG,"-----------doRemoveRemoteUi-");
                    AgoraUtils.checkSurfaceView(surfaceView);
                }

                MeetingManager.getInstance().removeSurfaceView(uid);

                if(uid==MeetingManager.getInstance().getRemoteUid())
                {
                    MeetingManager.getInstance().setRemoteUid(0);
                }

                //更新成员数据

                mMemAdapter.setList(MeetingManager.getInstance().getSurfaceKeys());
            }
        });
    }

    private void doRenderRemoteUi(final int uid) {

        Log.i(MeetingConfig.TAG,"doRenderRemoteUi begin");
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (isFinishing()) {
                    Log.i(MeetingConfig.TAG,"doRenderRemoteUi   isFinishing");
                    return;
                }

                SurfaceView surfaceView = MeetingManager.getInstance().getSurfaceViewById(uid);
                if(surfaceView==null)
                {
                    Log.i(MeetingConfig.TAG,"surfaceView==null ");
                    surfaceView = RtcEngine.CreateRendererView(getApplicationContext());
                    MeetingManager.getInstance().insertSurfaceView(uid,surfaceView);

                    if(MeetingManager.getInstance().getSurfaceViewNum()==2)
                    {
                        mBcLayout.addView(surfaceView,new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
                        MeetingManager.getInstance().setRemoteUid(uid);
                    }
                }
                else
                {
                    Log.i(MeetingConfig.TAG,"surfaceView !=null ");
                    AgoraUtils.checkSurfaceView(surfaceView);

                    if(MeetingManager.getInstance().getSurfaceViewNum()==2)
                    {
                        mBcLayout.addView(surfaceView,new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
                        MeetingManager.getInstance().setRemoteUid(uid);
                    }
                }

                if(mUserId==uid)
                {
                    Log.i(MeetingConfig.TAG,"------BROADCASTER_TYPE------设置本地------------------");
                    mRtcEngine.setupLocalVideo(new VideoCanvas(surfaceView, VideoCanvas.RENDER_MODE_HIDDEN, uid));
                }
                else
                {
                    Log.i(MeetingConfig.TAG,"------BROADCASTER_TYPE------远程------------------");
                    mRtcEngine.setupRemoteVideo(new VideoCanvas(surfaceView, VideoCanvas.RENDER_MODE_HIDDEN, uid));
                }

                mRtcEngine.setRemoteVideoStreamType(uid, Constants.VIDEO_STREAM_LOW);

                //更新成员数据
                int num = MeetingManager.getInstance().getSurfaceViewNum();
                Log.i(MeetingConfig.TAG,"id num:"+num);
                mMemAdapter.setList(MeetingManager.getInstance().getSurfaceKeys());
            }
        });
    }

    private void changeSurface(int uid)
    {
        if(mUserId==uid)
        {
            Toast.makeText(mContext,"当前选择为您自己，请选择其他成员",Toast.LENGTH_LONG).show();
            return;
        }

        int remoteId = MeetingManager.getInstance().getRemoteUid();
        if(remoteId!=0 && remoteId ==uid)
        {
            Toast.makeText(mContext,"当前选择已经显示，请选择其他成员",Toast.LENGTH_LONG).show();
            return;
        }

        if(remoteId!=0)
        {
            SurfaceView surfaceView = MeetingManager.getInstance().getSurfaceViewById(remoteId);
            if(surfaceView!=null)
            {
              AgoraUtils.checkSurfaceView(surfaceView);
            }

        }

        SurfaceView surfaceView2 = MeetingManager.getInstance().getSurfaceViewById(uid);
        if(surfaceView2!=null)
        {
            mBcLayout.addView(surfaceView2,new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            MeetingManager.getInstance().setRemoteUid(uid);
        }

    }


    public void onSendMsg(View view)
    {
        if(mAgoraSigAPI!=null)
        {

                String msgStr = mEditText.getText().toString();
                mMsgAdapter.setList(AgoraManager.getInstance().getMsgList());
                mEditText.setText("");

                Log.i(MeetingConfig.TAG,"onSendMsg:"+msgStr);
                mAgoraSigAPI.messageChannelSend(mRoomId,msgStr,"");

        }
    }

}
